package com.atguigu.ssyx.acl.service.impl;
import java.util.Date;

import com.atguigu.ssyx.acl.mapper.PermissionMapper;
import com.atguigu.ssyx.acl.mapper.RolePermissionMapper;
import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.acl.service.RolePermissionService;
import com.atguigu.ssyx.model.acl.Permission;
import com.atguigu.ssyx.model.acl.RolePermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 杨林
 * @create 2023-07-12 9:10 星期三
 * description:
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 根据roleId查询菜单
     * @param roleId
     */
    @Override
    public List<Permission> toAssign(Long roleId) {
        //查询所有的权限
        List<Permission> allMenu = permissionService.getAllMenu();
        //根据roleId查询当前角色已分配的权限
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RolePermission::getRoleId,roleId);
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(wrapper);
        //搜集已分配权限的权限id
        List<Long> permissionIds = new ArrayList<>();
        rolePermissions.forEach(item -> permissionIds.add(item.getPermissionId()));
        //在选有权限中将已经分配的权限标记为已选中状态
        //一下是Stream流
//        allMenu.forEach(item -> {
//            if (permissionIds.contains(item.getId())){
//                item.setSelect(true);
//            }
//        });
        return allMenu;
    }

    /**
     * 分配权限
     * @param roleId
     * @param permissionIds
     */
    @Transactional
    @Override
    public void doAssign(Long roleId, List<Long> permissionIds) {
        //删除当前角色的权限
        LambdaQueryWrapper<RolePermission> dWrapper = new LambdaQueryWrapper<>();
        dWrapper.eq(RolePermission::getRoleId,roleId);
        rolePermissionMapper.delete(dWrapper);
        //给当前角色分配权限
        //构建批量增加的List
        List<RolePermission> addList = new ArrayList<>();
        permissionIds.forEach(item -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(item);
            rolePermission.setCreateTime(new Date());
            rolePermission.setUpdateTime(new Date());
            rolePermission.setIsDeleted(0);
            addList.add(rolePermission);
        });
        this.saveBatch(addList);
    }
}
